<script setup>
import { registerApi } from '@/api/login'
import { changeEnterpriseStatusApi, enterpriseListQueryApi, getEnterpriseListApi } from '@/api/user'
import Form from '@/components/User/Form.vue'
import FormAdd from '@/components/common/formAdd.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/common/table.vue'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { utils, writeFileXLSX } from 'xlsx'
// 获取年份
const yearData = new Date().getFullYear()
const router = useRouter()
// 表单数据
const formData = ref({
  account: '',
  enterpriseName: '',
  industry: '',
  phone: '',
  status: ''
})
const formModel = [
  {
    prop: 'account',
    label: '账号',
    type: 'input'
  },
  {
    prop: 'enterpriseName',
    label: '企业名称',
    type: 'input'
  },
  {
    prop: 'industry',
    label: '所属行业',
    type: 'input'
  },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: '0' },
      { label: '禁用', value: '1' }
    ]
  },
  {
    prop: 'phone',
    label: '联系电话',
    type: 'input'
  }
]
const btnOpt = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '新增',
    btnType: 'success',
    prop: 'add'
  },
  {
    name: '导出',
    btnType: 'warning',
    prop: 'output'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  }
]
// ************************新增企业
// 对话框的显示隐藏
const dialogFormVisible = ref(false)
// 添加企业账号表单数据
const form = ref({
  identity: '企业',
  account: '',
  password: '',
  enterpriseName: '',
  enterpriseAddress: '',
  detailAddress: '',
  industry: '',
  detail: '',
  phone: ''
})

const studentFormOpt = [
  { label: '身份', type: 'input', prop: 'identity' },
  { label: '账号', type: 'input', prop: 'account' },
  { label: '密码', type: 'password', prop: 'password' },
  { label: '确认密码', type: 'password', prop: 'repassword' },
  { label: '企业名称', type: 'input', prop: 'enterpriseName' },
  { label: '企业地址', type: 'address', prop: 'enterpriseAddress' },
  { label: '详细地址', type: 'textarea', prop: 'detailAddress' },
  {
    label: '企业所属行业',
    type: 'select',
    prop: 'industry',
    options: [
      { value: '农、林、牧、渔业', label: '农、林、牧、渔业' },
      { value: '采矿业', label: '采矿业' },
      { value: '制造业', label: '制造业' },
      { value: '电力、热力、燃气及水的生产和供应业', label: '电力、热力、燃气及水的生产和供应业' },
      { value: '环境和公共设施管理业', label: '环境和公共设施管理业' },
      { value: '建筑业', label: '建筑业' },
      { value: '教育', label: '教育' },
      { value: '交通运输、仓储业和邮政业', label: '交通运输、仓储业和邮政业' },
      { value: '信息传输、计算机服务和软件业', label: '信息传输、计算机服务和软件业' },
      { value: '批发和零售业', label: '批发和零售业' },
      { value: '住宿、餐饮业', label: '住宿、餐饮业' },
      { value: '金融、保险业', label: '金融、保险业' },
      { value: '房地产业', label: '房地产业' },
      { value: '租赁和商务服务业', label: '租赁和商务服务业' },
      { value: '科学研究、技术服务和地质勘查业', label: '科学研究、技术服务和地质勘查业' },
      { value: '水利', label: '水利' },
      { value: '居民服务和其他服务业', label: '居民服务和其他服务业' },
      { value: '卫生、社会保障和社会服务业', label: '卫生、社会保障和社会服务业' },
      { value: '文化、体育、娱乐业', label: '文化、体育、娱乐业' },
      { value: '综合（含投资类、主业不明显）', label: '综合（含投资类、主业不明显）' },
      { value: '其它', label: '其它' }
    ]
  },
  { label: '企业详情', type: 'textarea', prop: 'detail' },
  {
    label: '联系电话',
    type: 'input',
    prop: 'phone'
  }
]
const btnOptStudent = [
  {
    name: '取消',
    btnType: '',
    prop: 'cancel'
  },
  {
    name: '确定',
    btnType: 'success',
    prop: 'confirm'
  }
]
const formRef = ref(null)
const pagizationToatl = ref(null)
const paginationRef = ref(null)
/**
 * 获取表格数据
 */
async function getTableData(data) {
  const res = await enterpriseListQueryApi(data)
  tableData.value = res.data
  tableData.value.forEach((item) => {
    item.enterpriseAddress = JSON.parse(item.enterpriseAddress).join('')
  })

  pagizationToatl.value = res.total
}
getTableData()
/**
 * 表单按钮添加事件
 */
function addForm() {
  dialogFormVisible.value = true
}
/**
 * 对话框取消事件
 */
function cancel() {
  formRef.value.reset()
  dialogFormVisible.value = false
}
/**
 * 对话框确定事件
 */
async function confirm(data) {
  const res = await registerApi(data)
  showStatusMessage(res)
  getTableData()
  // 关闭对话框
  dialogFormVisible.value = false
}
const selectFormRef = ref(null)
function reset() {
  getTableData()
  paginationRef.value.reset()
  selectFormRef.value.reset()
}
/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
// const queryData = ref(null)
/**
 * 条件查询
 * @param data
 */
async function query(data) {
  // console.log(data)

  // queryData.value = data
  const res = await enterpriseListQueryApi(data)
  // console.log(res)
  showStatusMessage(res)
  tableData.value = res.data
  tableData.value.forEach((item) => {
    item.enterpriseAddress = JSON.parse(item.enterpriseAddress).join('')
  })
  pagizationToatl.value = res.total
}
// 导出excel
async function exportToExcel() {
  // 获取要导出的业务数据
  const res = await getEnterpriseListApi()
  const data = res.data
  // 表头中文字段value
  const tableHeaderValues = [
    '账号',
    '企业名称',
    '企业地址',
    '企业所属行业',
    '企业详情',
    '练习电话',
    '账号状态'
  ]
  // 以excel表格的顺序调整后端数据
  const sheetData = data.map((item, index) => {
    let obj = {}
    obj = {
      account: item.account,
      enterpriseName: item.enterpriseName,
      enterpriseAddress: item.enterpriseAddress,
      industry: item.industry,
      detail: item.detail,
      phone: item.phone,
      status: item.status == 0 ? '启用' : '已禁用'
    }
    return obj
  })
  // 创建一个工作表
  const worksheet = utils.json_to_sheet(sheetData)
  // 创建一个新的工作簿
  const workbook = utils.book_new()
  // 把工作表添加到工作簿
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
  writeFileXLSX(workbook, `${new Date().toLocaleString()}导出数据.xlsx`)
}

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'add':
      addForm()
      break
    case 'output':
      exportToExcel()
      break
    case 'cancel':
      cancel()
      break
    case 'confirm':
      confirm(data)
      break
    case 'reset':
      reset()
      break

    default:
      break
  }
}
// 列表数据
const tableData = ref([])
const columns = [
  {
    prop: 'account',
    label: '账号'
  },
  {
    prop: 'enterpriseName',
    label: '企业名称'
  },
  {
    prop: 'enterpriseAddress',
    label: '地址'
  },
  {
    prop: 'status',
    label: '是否禁用'
  },
  {
    prop: 'industry',
    label: '所属行业'
  },

  {
    prop: 'phone',
    label: '联系电话'
  }
]
const options = [
  {
    label: '详情',
    type: 'success',
    prop: 'info'
  }
]

/**
 * 修改企业账号是否被禁用事件
 * @param data 0|1禁用状态
 */
async function handletTableSwitch(data) {
  console.log(data)
  const res = await changeEnterpriseStatusApi({ account: data.account, status: data.status })
  showStatusMessage(res)
}
const drawerisOpen = ref(false)
const drawerData = ref(null)
function handletTableInfo(data) {
  drawerisOpen.value = true
  console.log(data)
  drawerData.value = data
  //   {
  //     "id": 28,
  //     "account": "s123456",
  //     "enterpriseName": "机械制造",
  //     "enterpriseAddress": "北京市市辖区朝阳区",
  //     "detailAddress": "写字楼12层",
  //     "industry": "建筑业",
  //     "detail": "专注于建筑材料制造",
  //     "image_url": "http://127.0.0.1:3007/upload/733337e4-c17a-40d4-9ba4-34b212d34827_th.jpg",
  //     "phone": "112456789",
  //     "status": 0,
  //     "jobPublish": 2,
  //     "license": "",
  //     "identity": "企业"
  // }
}

/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-'edit'-'delete'
 */
function handleTable(data, type) {
  switch (type) {
    // 修改账号是否被禁用
    case 'switch':
      handletTableSwitch(data)
      break
    case 'info':
      handletTableInfo(data)
      break

    default:
      break
  }
}
// 分页器条数发生变化
function handleSizeChange(val) {
  console.log('条数发生变化')
  getTableData({ size: val })
  paginationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  console.log('页数发生变化')
  getTableData({ page, size })
}
function handleDrawerClose() {
  drawerData.value = {}
  drawerisOpen.value = false
}
</script>

<template>
  <div class="user-wrapper">
    <div class="user-content">
      <Form
        :data="formData"
        :formOpt="formModel"
        :btnOpt="btnOpt"
        @handleForm="handleForm"
        ref="selectFormRef"
      ></Form>
      <!-- 表格 -->
      <Table
        :tableData="tableData"
        :columns="columns"
        :options="options"
        @handleTable="handleTable"
      >
        <template #firstColumn>
          <el-table-column type="index" label="用户编号" width="100" align="center" />
        </template>
      </Table>
      <!-- 分页 -->
      <Pagization
        ref="paginationRef"
        :total="pagizationToatl"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></Pagization>
    </div>
    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="新增学生用户"
      width="500"
      :close-on-click-modal="false"
      align-center
      destroy-on-close
    >
      <FormAdd
        ref="formRef"
        :data="form"
        :formOpt="studentFormOpt"
        :btnOpt="btnOptStudent"
        @handleForm="handleForm"
      ></FormAdd>
    </el-dialog>
    <!-- 弹出框 -->
    <el-drawer
      v-model="drawerisOpen"
      title="企业详情"
      :size="500"
      :with-header="true"
      @close="handleDrawerClose"
    >
      <div class="drawer-content">
        <div class="info-section">
          <div class="section-title">基本信息</div>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">企业账号：</span>
              <span class="value">{{ drawerData?.account }}</span>
            </div>
            <div class="info-item">
              <span class="label">企业名称：</span>
              <span class="value">{{ drawerData?.enterpriseName }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ drawerData?.phone }}</span>
            </div>
            <div class="info-item">
              <span class="label">账号状态：</span>
              <span
                class="value"
                :class="drawerData?.status === 0 ? 'status-active' : 'status-inactive'"
              >
                {{ drawerData?.status === 0 ? '启用' : '禁用' }}
              </span>
            </div>
          </div>
        </div>

        <div class="info-section">
          <div class="section-title">企业信息</div>
          <div class="info-block">
            <div class="info-row">
              <div class="info-item">
                <span class="label">所属行业</span>
                <span class="value">{{ drawerData?.industry }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <span class="label">企业地址</span>
                <span class="value">{{ drawerData?.enterpriseAddress }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <span class="label">详细地址</span>
                <span class="value">{{ drawerData?.detailAddress }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <span class="label">企业详情</span>
                <div class="value-box">{{ drawerData?.detail }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="info-section" v-if="drawerData?.image_url || drawerData?.license">
          <div class="section-title">企业资质</div>
          <div class="image-grid">
            <div class="image-item" v-if="drawerData?.image_url">
              <div class="image-label">企业头像</div>
              <el-image
                :src="drawerData.image_url"
                :preview-src-list="[drawerData.image_url]"
                fit="cover"
              />
            </div>
            <div class="image-item" v-if="drawerData?.license">
              <div class="image-label">营业执照</div>
              <el-image
                :src="drawerData.license"
                :preview-src-list="[drawerData.license]"
                fit="cover"
              />
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.user-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: start;
  .user-content {
    width: 100%;
    padding: 30px 50px;
    text-align: left;
    overflow: auto;
  }
}

.drawer-content {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;

  .info-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 20px;
      padding-left: 10px;
      border-left: 4px solid #409eff;
    }

    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
    }

    .info-block {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .info-row {
        padding: 8px 12px;
        border-radius: 4px;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f7fa;
        }

        .info-item {
          display: flex;
          align-items: flex-start;
          gap: 12px;

          .label {
            min-width: 70px;
            font-size: 14px;
            color: #909399;
            font-weight: 500;
          }

          .value {
            flex: 1;
            font-size: 14px;
            color: #303133;
            line-height: 1.6;
          }

          .value-box {
            flex: 1;
            font-size: 14px;
            color: #303133;
            line-height: 1.6;
            padding: 12px;
            background-color: #fff;
            border-radius: 4px;
            border: 1px solid #e4e7ed;
            min-height: 80px;
          }
        }
      }
    }
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;

    .image-item {
      .image-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }

      :deep(.el-image) {
        width: 100%;
        height: 200px;
        border-radius: 4px;
        cursor: pointer;
        transition: transform 0.3s;
        border: 1px solid #e4e7ed;

        &:hover {
          transform: scale(1.02);
        }
      }
    }
  }
}
</style>
